package dbops

import (
	"gitee.com/DengAnbang/Computation/src/bean"
	"gitee.com/DengAnbang/goutils/utils"
	"gitee.com/DengAnbang/goutils/dbutils"
	"database/sql"

	"gitee.com/DengAnbang/goutils/loge"
)

func CreateTree(treeName, createdId, typeTree, sort, code, no string) (tree bean.TreeBean, err error) {
	return CreateTreeByUuid(utils.NewUUID(), treeName, createdId, typeTree, sort, code, no)
}
func CreateTreeByUuid(uuid, treeName, createdId, typeTree, sort, code, no string) (tree bean.TreeBean, err error) {
	if len(treeName) == 0 {
		return tree, bean.NewErrorMessage("名称不能为空")
	}
	if len(createdId) == 0 {
		return tree, bean.NewErrorMessage("创建人ID为空")
	}
	if len(sort) == 0 {
		return tree, bean.NewErrorMessage("sort为空")
	}
	if len(code) == 0 {
		return tree, bean.NewErrorMessage("code为空")
	}
	if len(typeTree) == 0 {
		return tree, bean.NewErrorMessage("树的类型为空")
	}
	stmtIn, err := dbConn.Prepare("INSERT INTO table_tree (tree_id,node_id,node_name,node_parent_id,created_id,depth,sort,code,no)VALUES(?,?,?,?,?,?,?,?,?)")
	if err != nil {
		return
	}
	_, err = stmtIn.Exec(uuid, uuid, treeName, "", createdId, "0", sort, code, no)
	if err != nil {
		return
	}
	stmtIn.Close()
	tree, _ = SelectTreeNode(uuid)
	//加入到树的用户便
	stmtIn, err = dbConn.Prepare("INSERT INTO table_user_tree (tree_id,tree_user,tree_type,created_id)VALUES(?,?,?,?)")
	if err != nil {
		return
	}
	_, err = stmtIn.Exec(tree.TreeId, createdId+",", typeTree, createdId)

	//loge.DE(bean.NewSucceedMessage(code.TypeTreeCreate, tree).GetJson())
	return
}
func GetUserTreeList(userId, typeTree string) (tree []bean.CreatedTreeBean, err error) {
	var treeList = make([]bean.CreatedTreeBean, 0, 8)
	if len(userId) == 0 {
		return treeList, bean.NewErrorMessage("ID为空")
	}

	stmtOut, err := dbConn.Prepare("SELECT * FROM table_user_tree u JOIN table_tree t ON u.tree_id=t.tree_id WHERE tree_user LIKE ? AND tree_type =?")
	rows, err := stmtOut.Query("%"+userId+",%", typeTree)
	if err != nil {
		return treeList, err
	}
	defer rows.Close()
	for rows.Next() {
		var strings map[string]string
		strings, err = dbutils.GetRowsMap(rows)
		if err == nil {
			tree := bean.CreatedTreeBean{
				TreeBean:  bean.TreeBean{}.SetData(strings),
				CreatedId: strings["created_id"],
			}
			treeList = append(treeList, tree)
		} else {
			loge.W(err)
		}
	}
	//loge.DE(bean.NewSucceedMessage(code.TypeGetUserTreeList, treeList).GetJson())
	return treeList, nil
}
func RenameTreeNode(nodeId, newName string) (tree bean.TreeBean, err error) {
	if len(nodeId) == 0 {
		return tree, bean.NewErrorMessage("节点ID不能为空")
	}
	if len(newName) == 0 {
		return tree, bean.NewErrorMessage("名称不能为空")
	}

	stmtIn, err := dbConn.Prepare("UPDATE  table_tree SET node_name=? WHERE node_id=?")
	if err != nil {
		return
	}
	_, err = stmtIn.Exec(newName, nodeId)
	defer stmtIn.Close()
	tree, _ = SelectTreeNode(nodeId)
	//loge.DE(bean.NewSucceedMessage(code.TypeRenameNode, tree).GetJson())
	return
}
func AddTreeNode(treeName, nodeParentId, createdId, sort, code, no string) (tree bean.TreeBean, err error) {
	if len(treeName) == 0 {
		return tree, bean.NewErrorMessage("名称不能为空")
	}
	if len(nodeParentId) == 0 {
		return tree, bean.NewErrorMessage("父树的ID不能为空")
	}
	if len(createdId) == 0 {
		return tree, bean.NewErrorMessage("创建人的ID不能为空")
	}
	if len(sort) == 0 {
		return tree, bean.NewErrorMessage("sort不能为空")
	}
	if len(code) == 0 {
		return tree, bean.NewErrorMessage("code不能为空")
	}
	if len(no) == 0 {
		return tree, bean.NewErrorMessage("序号不能为空")
	}
	parentTree, _ := SelectTreeNode(nodeParentId)
	if len(parentTree.NodeId) <= 0 {
		return tree, bean.NewErrorMessage("父节点不存在")
	}
	//created := time.Now().Format("2006-01-02 15:03:04")
	uuid := utils.NewUUID()

	stmtIn, err := dbConn.Prepare("INSERT INTO table_tree (tree_id,node_id,node_name,node_parent_id,created_id,depth,sort, code,no)VALUES(?,?,?,?,?,?,?,?,?)")
	if err != nil {
		return
	}
	_, err = stmtIn.Exec(parentTree.TreeId, uuid, treeName, nodeParentId, createdId, utils.String2int(parentTree.Depth, 0)+1, sort, code, no)
	defer stmtIn.Close()
	tree, _ = SelectTreeNode(uuid)
	//loge.DE(bean.NewSucceedMessage(code.TypeTreeAddNode, tree).GetJson())
	return
}

func DeleteTreeNode(nodeId string) (err error) {
	if len(nodeId) == 0 {
		return bean.NewErrorMessage("删除的节点ID不能为空")
	}
	treeBean, err := SelectTreeNode(nodeId)
	beans, err := SelectTreeNodeList(nodeId, false)
	if err != nil {
		return
	}
	for _, v := range beans {
		DeleteTreeNode(v.NodeId)
	}
	stmtIn, err := dbConn.Prepare("DELETE FROM table_tree WHERE node_id=? OR node_parent_id=?")
	if err != nil {
		return
	}
	_, err = stmtIn.Exec(nodeId, nodeId)
	stmtIn.Close()
	if treeBean.TreeId == treeBean.NodeId {
		stmtIn, err := dbConn.Prepare("DELETE FROM table_user_tree WHERE tree_id=?")
		if err != nil {
			return err
		}
		_, err = stmtIn.Exec(nodeId)
		stmtIn.Close()
	}
	//loge.DE(bean.NewSucceedMessage(code.TypeTreeDeleteNode, "删除成功").GetJson())
	return
}
func SelectTreeNode(nodeId string) (bean.TreeBean, error) {
	var user bean.TreeBean
	stmtOut, err := dbConn.Prepare("SELECT * FROM table_tree WHERE node_id = ?")
	if err != nil {
		return user, err
	}
	defer stmtOut.Close()
	rows, err := stmtOut.Query(nodeId)
	if err != nil {
		return user, err
	}
	defer rows.Close()
	if rows.Next() {
		var strings map[string]string
		strings, err = dbutils.GetRowsMap(rows)
		if err != nil {
			return user, err
		}
		user = bean.TreeBean{}.SetData(strings)
	}
	return user, err
}

/**
isWhole =true 查询完整的树
isWhole =false 仅查询nodeId的子节点(一级)
 */
func SelectTreeNodeList(nodeId string, isWhole bool) ([]bean.TreeBean, error) {
	if len(nodeId) == 0 {
		return nil, bean.NewErrorMessage("节点ID不能为空")
	}
	var treeList = make([]bean.TreeBean, 0, 8)
	var err error
	var stmtOut *sql.Stmt
	if isWhole {
		stmtOut, err = dbConn.Prepare("SELECT * FROM table_tree WHERE tree_id = ?")
	} else {
		stmtOut, err = dbConn.Prepare("SELECT * FROM table_tree WHERE node_parent_id = ?")
	}

	if err != nil {
		return treeList, err
	}
	defer stmtOut.Close()
	rows, err := stmtOut.Query(nodeId)
	if err != nil {
		return treeList, err
	}
	defer rows.Close()
	for rows.Next() {
		var strings map[string]string
		strings, err = dbutils.GetRowsMap(rows)
		if err == nil {
			tree := bean.TreeBean{}.SetData(strings)
			treeList = append(treeList, tree)
		} else {
			loge.W("SelectTreeNodeList err:nodeId=%s,isWhole=%v,err:%v", nodeId, isWhole, err)
		}

	}
	//loge.DE(bean.NewSucceedMessage(code.TypeTreeSelectNodeList, treeList).GetJson())
	return treeList, err
}
